package vn.edu.uit.game_show.utilities;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import vn.edu.uit.chemistry.protocol.CapNhatGame;
import vn.edu.uit.chemistry.protocol.Message;
import vn.edu.uit.chemistry.protocol.ThongTinCaNhan;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

public class TCPClient implements Runnable {

	Context ctx;
	Socket sk;
	String host = "";
	int port = 0;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;

	public TCPClient(Context _ctx, String _host, int _port)
			throws UnknownHostException, IOException {
		this.ctx = _ctx;
		this.host = _host;
		this.port = _port;
		sk = new Socket(host, port);
		oos = new ObjectOutputStream(sk.getOutputStream());
		ois = new ObjectInputStream(sk.getInputStream());
	}

	public void stop() throws IOException {
		oos.close();
		ois.close();
		sk.close();
	}

	public void guiThongTin() throws IOException, ClassNotFoundException {
		SharedPreferences prefs = ctx.getSharedPreferences("TaiKhoanNhom", 0);
		String tenHS = prefs.getString("tenNhom", "").toString();
		String ipHS = prefs.getString("ip", "").toString();
		String portHS = prefs.getString("port", "").toString();

		oos.writeObject(new ThongTinCaNhan(tenHS, "", ipHS, portHS));

		Message msg = (Message) ois.readObject();

		if (msg instanceof ThongTinCaNhan) {
			//Toast.makeText(ctx, "Da nhan Phan hoi", Toast.LENGTH_LONG).show();
		}
	}
	
	public void guiKetQuaGame(String result) throws IOException {
		SharedPreferences prefs = ctx.getSharedPreferences("TaiKhoanNhom", 0);
		String tenHS = prefs.getString("tenNhom", "").toString();
		String ipHS = prefs.getString("ip", "").toString();

		oos.writeObject(new CapNhatGame(tenHS, ipHS, result));
	}

	public void run() {
		// TODO Auto-generated method stub

	}
}
